﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using NetTaste;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Logging;
using System.Linq.Expressions;
using NPOI.SS.Formula.Functions;
using DFGK_WMS.Model.Enum;

namespace DFGK_WMS.Repository
{
    /// <summary>
    /// 出库管理
    /// </summary>
    public class TShippingOrderDetailRepository : BaseRepository<TShippingOrderDetail>, ITShippingOrderDetailRepository
    {
        private readonly ITShippingLockCellRepository lockCellRepository;

        public TShippingOrderDetailRepository(DFGK_DB context, IMapper mapper,ITShippingLockCellRepository lockCellRepository) : base(context, mapper)
        {
            this.lockCellRepository = lockCellRepository;
        }

        #region 添加出库单弃用
        /*
        /// <summary>
        /// 添加出库管理
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTShippingOrderDetail(TShippingOrderDetail model)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    //订单号
                    //单据类型
                    //合同号
                    //物料分类 优先级为顶级 默认为0
                    //物料名称
                    var material = Context.TMaterials.Find(model.MaterialId);
                    if (material != null)
                    {
                        model.MaterialCode = material.Code;
                        model.MaterialName = material.Name;
                        model.MaterialTypeCode = material.TypeCode;
                        model.UnitId = material.UnitId;
                        model.UnitName = material.UnitName;
                    }

                    ////物料批次信息
                    //// 根据 MaterialId 和 MaterialName 查询对应的物料批次记录
                    //var materialkey = Context.TMaterialKeys.FirstOrDefault(m =>
                    //    m.MaterialId == model.MaterialId && m.MaterialName == model.MaterialName);
                    //if (materialkey != null)
                    //{
                    //    model.BatchNo = materialkey.BatchNo;
                    //}

                    //库房信息
                    var house = Context.TWarehouses.Find(model.WarehouseId);
                    if (house != null)
                    {
                        model.WarehouseCode = house.Code;
                        model.WarehouseName = house.Name;                      
                    }                

                    //出库数默认为0
                    model.PickedQty = model.Qty;
                    model.ShippedQty = 0;
                    model.Status = 0;
                    //部门
                    var userobj = Context.TUsers.Find(model.NowUserId);
                    if (userobj != null)
                    {
                        var deptobj = Context.TDepartments.Find(userobj.DepartmentId);
                        if (deptobj != null)
                        {
                            model.DeptName = deptobj.DepartmentName;
                            model.DeptCode = deptobj.DepartmentCode;
                        }
                    }

                    #region 审计字段

                    model.CreateUserId = model.NowUserId;
                    model.CreateUserName = model.NowUserRealName;
                    model.CreateDate = DateTime.Now;
                    model.ModifyUserId = model.NowUserId;
                    model.ModifyUserName = model.NowUserRealName;
                    model.ModifyDate = DateTime.Now;
                    model.AuditUserId = model.NowUserId;
                    model.AuditUserName = model.NowUserRealName;
                    model.AuditDate = DateTime.Now;
                    model.SubmitUserId = model.NowUserId;
                    model.SubmitUserName = model.NowUserRealName;
                    model.SubmitDate = DateTime.Now;

                    #endregion 审计字段

                    //供应商
                    var supper = Context.TSuppliers.Find(model.SupplierId);
                    if (supper != null)
                    {
                        model.SupplierName = supper.Name;
                    }
                
                    Context.TShippingOrderDetails.Add(model);
                    Context.SaveChanges();

                    

                    //货位锁定明细
                    foreach (var item in model.LockCell)
                    {
                        var inv = Context.TInventories.Where(s => s.Id == item.InventoryId).FirstOrDefault();
                        inv.Status = 4;
                        //item.AvailableQty = item.AvailableQty - item.OutQty;
                        Context.TInventories.Update(inv);
                        //货位锁定明细
                        TShippingLockCell m = new TShippingLockCell();
                        m.OrderDetailId = model.Id;
                        m.InventoryId = item.InventoryId;
                        m.CellId = item.CellId;
                        m.CellCode = item.CellCode;
                        m.CellName = item.CellName;
                        m.PalletBarcode = item.PalletBarcode;
                        m.WhId = model.WarehouseId;
                        m.CellDepthIndex = 0;
                        //组垛Id不知道
                        m.StackingStorageId = 0;
                        m.OutQty = item.OutQty;
                        m.InventoryQty = item.InventoryQty;
                        m.MaterialId = item.MaterialId;
                        m.MaterialName = item.MaterialName;
                        m.MaterialCode = item.MaterialCode;
                        m.MaterialKeyId = item.MaterialKeyId;
                        m.BatchNo = item.BatchNo;
                        m.CreateDate = DateTime.Now;
                        m.RoutewayId = item.RoutewayId;
                        Context.TShippingLockCells.Add(m);

                        // 添加货品表
                        TShippingGoodsDetail product = new TShippingGoodsDetail();
                        product.OrderDetailId = model.Id;
                        product.MaterialId = item.MaterialId;
                        product.MaterialCode = item.MaterialCode;
                        product.MaterialName = item.MaterialName;
                        product.Status = 0;
                        product.PalletBarcode = item.PalletBarcode;
                        Context.TShippingGoodsDetails.Add(product);

                        Context.SaveChanges();
                    }

                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }

        /// <summary>
        /// 添加出库管理 多个物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool AddTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model,out string msg)
        {
            msg = "添加成功";
            using (var tran = Context.Database.BeginTransaction())
            {
                try
                {
                    foreach (var mater in model.ShippingOrderDetailPlusLockCellDTOs)
                    {
          
                        //客户
                        var cust = Context.TCustomers.Find(model.CustomerId);
                        if (cust == null)
                        {
                            msg = "找不到客户";
                            return false;
                        }

                        //为了查询物料typeCode
                        var material = Context.TMaterials.Find(mater.MaterialId);
                        if (material == null)
                        {
                            msg = "找不到此物料";
                            return false;
                        }

                        var invmter = Context.TInventories.Where(s => s.MaterialId == mater.MaterialId);
                        if (invmter == null || invmter.Count() <= 0)
                        {
                            msg = "库存中没有此物料";
                            return false;
                        }

                        var invSum = GetMaterialIdById(mater.MaterialId).MaxCount;
                        if (mater.MaterialNum > invSum)
                        {
                            msg = mater.MaterialName + "库存数量不足，"+"最多可出"+ invSum;
                        }

                        var lockCell = lockCellRepository.LockCell(mater.MaterialId, mater.MaterialNum, out var lockCellList, out var errorMsg);
                        if (!lockCell)
                        {
                            return false;
                        }

                        TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail();
                        shippingOrderDetail.OrderSn = model.OrderSn; //同一个订单号
                        shippingOrderDetail.SupplierId = cust.Id;  // 拿供应商当客户用！
                        shippingOrderDetail.SupplierName=cust.Name;
                        shippingOrderDetail.MaterialId=mater.MaterialId;
                        shippingOrderDetail.MaterialName = mater.MaterialName;
                        shippingOrderDetail.MaterialTypeCode = material.TypeCode;
                        shippingOrderDetail.BillType = model.BillType;
                        shippingOrderDetail.WarehouseCode = "";
                        shippingOrderDetail.WarehouseName = "";
                        shippingOrderDetail.AreaCode = "";
                        shippingOrderDetail.AreaName = "";
                        shippingOrderDetail.BatchNo = "";
                        shippingOrderDetail.UnitName = material.UnitName;
                        shippingOrderDetail.Qty = mater.MaterialNum;
                        shippingOrderDetail.Status = 0 ;
                        shippingOrderDetail.StationName = "";
                        shippingOrderDetail.CreateDate = DateTime.Now;
                        shippingOrderDetail.CreateUserName = model.NowUserRealName;
                        shippingOrderDetail.CreateUserId = model.NowUserId;

                        
                        Context.TShippingOrderDetails.Add(shippingOrderDetail);
                        Context.SaveChanges();

                        // 添加货品表
                        TShippingGoodsDetail product = new TShippingGoodsDetail();
                        product.OrderDetailId = shippingOrderDetail.Id;
                        product.MaterialId = mater.MaterialId;
                        product.MaterialCode = mater.MaterialCode;
                        product.MaterialName = mater.MaterialName;
                        product.Status = 0;
                        Context.TShippingGoodsDetails.Add(product);
                        Context.SaveChanges();

                        //货位锁定明细
                        foreach (var item in lockCellList)
                        {
                            var inv = Context.TInventories.Where(s => s.Id == item.InventoryId).FirstOrDefault();
                            if (inv == null)
                                return false;
                            inv.Status = 4;
                            Context.TInventories.Update(inv);
                            //货位锁定明细
                            TShippingLockCell m = new TShippingLockCell();
                            m.OrderDetailId = shippingOrderDetail.Id;
                            m.InventoryId = item.InventoryId;
                            m.CellId = item.CellId;
                            m.CellCode = item.CellCode;
                            m.CellName = item.CellName;
                            m.PalletBarcode = item.PalletBarcode;
                            m.WhId = item.WhId;
                            m.CellDepthIndex = 0;
                            m.StackingStorageId = item.StackingStorageId;
                            m.OutQty = item.OutQty;
                            m.InventoryQty = item.InventoryQty;
                            m.MaterialId = item.MaterialId;
                            m.MaterialName = item.MaterialName;
                            m.MaterialCode = item.MaterialCode;
                            m.MaterialKeyId = item.MaterialKeyId;
                            m.BatchNo = item.BatchNo;
                            m.CreateDate = DateTime.Now;
                            m.RoutewayId = item.RoutewayId;
                            m.IsPicking = false;
                            Context.TShippingLockCells.Add(m);
                            Context.SaveChanges();
                        }
                    }
                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }
                */
        #endregion


        /// <summary>
        /// 添加出库单
        /// </summary>
        /// <param name="m"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool AddTShippingOrderDetail(GroupShippingOrderDto m, out string message)
        {
            message = "";
            foreach (var item in m.childShippingOrders)
            {
                TShippingOrderDetail shippingOrderDetail = new TShippingOrderDetail();
                shippingOrderDetail.BillType = m.BillType;
                shippingOrderDetail.OrderSn = m.OrderSn;
                shippingOrderDetail.RelevanceOrderSn = m.RelevanceOrderSn;
                shippingOrderDetail.Agent = m.Agent;
                shippingOrderDetail.SupplierId = m.SupplierId;
                var list = Context.TSuppliers.Where(x => x.Id == m.SupplierId).ToList();
                shippingOrderDetail.SupplierName = list != null && list.Any() ? list.FirstOrDefault().Name : null;
                shippingOrderDetail.CreateDate = DateTime.Now;

                shippingOrderDetail.MaterialCategoryName = "";
                shippingOrderDetail.MaterialId = item.MaterialId; 
                shippingOrderDetail.MaterialName = "";
                shippingOrderDetail.ModelSpec = item.ModelSpec;
                shippingOrderDetail.QualityState = 1;//质量等级
                shippingOrderDetail.Qty = item.Qty;

                #region 审计字段

                #endregion
                Context.TShippingOrderDetails.Add(shippingOrderDetail);

            }
            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 删除出库表
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DeleteTShippingOrderDetail(int id)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                var deleteModel = Context.TShippingOrderDetails.Find(id);
                var delShip = Context.TShippingLockCells.Where(s => s.OrderDetailId == id);
                var updInvList = new List<TInventory>();
                if (deleteModel != null && delShip!=null)
                {
                    Context.TShippingOrderDetails.Remove(deleteModel);
                    //删除被锁定的仓位信息表
                    Context.TShippingLockCells.RemoveRange(delShip);
                    foreach (var item in delShip)
                    {
                        var invs = Context.TInventory.Find(item.InventoryId);
                        if (invs != null)
                        {
                            invs.Status = 1;
                            updInvList.Add(invs);
                        }
                    }
                    Context.TInventory.UpdateRange(updInvList);
                    if (Context.SaveChanges() > 0)
                    {
                        tran.Commit();
                        return true;
                    }
                    return false;
                }
                else
                {
                    // 找不到对应的记录，返回删除失败
                    //事务回滚
                    tran.Rollback();
                    return false;
                }
  
            }
            catch (Exception ex)
            {
                //事务回滚
                tran.Rollback();
                // 处理异常，如记录日志等
                return false;
            }
        }

        // 根据OrderSn查询ID
        private List<int> GetTShippingOrderDetailId (string OrderSn)
        {
            List<int> listInt = new List<int>();

            var list = Context.TShippingOrderDetails.Where(x => x.OrderSn == OrderSn);

            if (list == null)
            {
                return listInt;
            }
            foreach (var item in list)
            {
                listInt.Add(item.Id);
            }
            return listInt;
        }


        /// <summary>
        /// 删除出库表  多个物料版本
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DeleteTShippingOrderDetailPlus(TShippingOrderDetailPlusDTO model)
        {
            using var tran = Context.Database.BeginTransaction();
            try
            {
                var deleteModel = Context.TShippingOrderDetails.Where(x => x.OrderSn == model.OrderSn);
                // 根据OrderSn查询ID
                var list = GetTShippingOrderDetailId(model.OrderSn);


                foreach (var TShippingLockCellsDetilsId in list)
                {
                    var delShip = Context.TShippingLockCells.Where(s => s.OrderDetailId == TShippingLockCellsDetilsId);
                    var updInvList = new List<TInventory>();
                    if (deleteModel != null && delShip != null)
                    {
                        foreach(var item in deleteModel)
                        {
                           var sta =  Context.TShippingOrderDetails.Remove(item);
                            if (sta == null)
                            {
                                tran.Rollback();
                                return false;
                            }
                        }
                        //删除被锁定的仓位信息表
                         Context.TShippingLockCells.RemoveRange(delShip);
                       //bool result =  Context.SaveChanges()>0;
                        //if (!result)
                        //{
                        //    tran.Rollback();
                        //}

                        foreach (var item in delShip.ToList())
                        {
                            var invs = Context.TInventory.Find(item.InventoryId);
                            if (invs != null)
                            {
                                invs.Status = 1;
                                updInvList.Add(invs);
                            }
                        }
                        Context.TInventory.UpdateRange(updInvList);
                       
                    }
                    else
                    {
                        // 找不到对应的记录，返回删除失败
                        //事务回滚
                        tran.Rollback();
                        return false;
                    }
                }
                if (Context.SaveChanges() > 0)
                {
                    tran.Commit();
                    return true;
                }
                return false;

            }
            catch (Exception ex)
            {
                //事务回滚
                tran.Rollback();
                // 处理异常，如记录日志等
                return false;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTShippingOrderDetail(TShippingOrderDetail model)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                var updateModel = Context.TShippingOrderDetails.Find(model.Id);
                if (updateModel == null)
                {
                    throw new Exception("要更新的记录不存在");
                }

                try
                {
                    //订单号
                    //单据类型
                    //合同号
                    //物料分类 优先级为顶级 默认为0
                    //物料名称
                    var material = Context.TMaterials.Find(model.MaterialId);
                    if (material != null)
                    {
                        updateModel.MaterialCode = material.Code;
                        updateModel.MaterialName = material.Name;
                        updateModel.MaterialTypeCode = material.TypeCode;
                        updateModel.UnitId = material.UnitId;
                        updateModel.UnitName = material.UnitName;
                    }

                    //// 物料批次信息
                    //// 根据 MaterialId 和 MaterialName 查询对应的物料批次记录
                    //var materialkey = Context.TMaterialKeys.FirstOrDefault(m =>
                    //    m.MaterialId == model.MaterialId && m.MaterialName == model.MaterialName);
                    //if (materialkey != null)
                    //{
                    //    updateModel.BatchNo = materialkey.BatchNo;
                    //}

                    // 获取库房信息
                    var house = Context.TWarehouses.Find(model.WarehouseId);

                    if (house != null)
                    {
                        updateModel.WarehouseCode = house.Code;
                        updateModel.WarehouseName = house.Name;                     
                    }                
                    //出库数默认为0
                    updateModel.Qty = model.Qty;
                    updateModel.PickedQty = updateModel.Qty;
                    updateModel.ShippedQty = updateModel.Qty;
                    updateModel.Status = model.Status;


                    #region 审计字段

                    updateModel.CreateUserId = model.NowUserId;
                    updateModel.CreateUserName = model.NowUserRealName;
                    updateModel.CreateDate = DateTime.Now;
                    updateModel.ModifyUserId = model.NowUserId;
                    updateModel.ModifyUserName = model.NowUserRealName;
                    updateModel.ModifyDate = DateTime.Now;
                    updateModel.AuditUserId = model.NowUserId;
                    updateModel.AuditUserName = model.NowUserRealName;
                    updateModel.AuditDate = DateTime.Now;
                    updateModel.SubmitUserId = model.NowUserId;
                    updateModel.SubmitUserName = model.NowUserRealName;
                    updateModel.SubmitDate = DateTime.Now;

                    #endregion 审计字段

                    //供应商
                    var supper = Context.TSuppliers.Find(model.SupplierId);
                    if (supper != null)
                    {
                        updateModel.SupplierName = supper.Name;
                    }
                
                    Context.TShippingOrderDetails.Update(updateModel);
                    Context.SaveChanges();

                    // 先删除原有货位锁定的明细信息
                    var updateLockCells = Context.TShippingLockCells.Where(x => x.OrderDetailId == updateModel.Id)
                        .ToList();
                    Context.TShippingLockCells.RemoveRange(updateLockCells);
                    // 添加新的货位锁定明细信息
                    foreach (var item in model.InventoryList)
                    {
                        item.AvailableQty = item.AvailableQty - item.OutQty;

                        // 更新库存信息
                        Context.TInventories.Update(item);

                        // 新增货位锁定明细信息
                        TShippingLockCell m = new TShippingLockCell();
                        m.OrderDetailId = model.Id;
                        m.InventoryId = item.Id;
                        m.CellId = item.LocationId;
                        m.CellCode = item.LocationCode;
                        m.CellName = item.LocationName;
                        m.PalletBarcode = item.PalletBarcode;
                        m.WhId = model.WarehouseId;
                        m.CellDepthIndex = 0;
                        m.StackingStorageId = 0;
                        m.OutQty = item.OutQty;
                        m.InventoryQty = item.AvailableQty;
                        m.MaterialId = item.MaterialId;
                        m.MaterialName = item.MaterialName;
                        m.MaterialCode = item.MaterialCode;
                        m.BatchNo = item.BatchNo;
                        m.CreateDate = DateTime.Now;
                        m.RoutewayId = item.RoutewayId;

                        Context.TShippingLockCells.Add(m);
                        Context.SaveChanges();
                    }

                    //无异常提交事务
                    tran.Commit();
                    return true;
                }
                catch (Exception)
                {
                    //事务回滚
                    tran.Rollback();
                    throw;
                }
            }
        }


        /// <summary>
        /// 修改出库单  多物料版本
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateTshippingOrderDetailPlus(TShippingOrderDetailPlusDTO models)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                int id = 0;
                foreach (var model in models.ShippingOrderDetailPlusLockCellDTOs)
                {
                    //var updateModel = Context.TShippingOrderDetails.FirstOrDefault(x => x.OrderSn ==  models.OrderSn);
                    var updateModel = Context.TShippingOrderDetails.FirstOrDefault(x => x.Id == model.TShippingLockCellsId);
                    if (updateModel == null)
                    {
                        throw new Exception("要更新的记录不存在");
                    }

                    try
                    {
                        //订单号
                        //单据类型
                        //合同号
                        //物料分类 优先级为顶级 默认为0
                        //物料名称
                        var material = Context.TMaterials.Find(model.MaterialId);
                        if (material != null)
                        {
                            updateModel.MaterialId = material.Id;
                            updateModel.MaterialCode = material.Code;
                            updateModel.MaterialName = material.Name;
                            updateModel.MaterialTypeCode = material.TypeCode;
                            updateModel.UnitId = material.UnitId;
                            updateModel.UnitName = material.UnitName;
                        }

                        //// 物料批次信息
                        //// 根据 MaterialId 和 MaterialName 查询对应的物料批次记录
                        //var materialkey = Context.TMaterialKeys.FirstOrDefault(m =>
                        //    m.MaterialId == model.MaterialId && m.MaterialName == model.MaterialName);
                        //if (materialkey != null)
                        //{
                        //    updateModel.BatchNo = materialkey.BatchNo;
                        //}


                        //客户
                        var cust = Context.TCustomers.Find(models.CustomerId);
                        if (cust != null)
                        {
                            updateModel.CreateUserName = cust.CreateUserName;
                        }

                        updateModel.BillType = models.BillType;
                        Context.TShippingOrderDetails.Update(updateModel);
                        Context.SaveChanges();

                        
                    }
                    catch (Exception)
                    {
                        //事务回滚
                        tran.Rollback();
                        throw;
                    }
                }
                //无异常提交事务
                tran.Commit();
                return true;
            }
        }

        /// <summary>
        /// 根据Id查看
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public TShippingOrderDetail GetByIdTShippingOrderDetail(int id)
        {
            // 根据ID查找出库管理记录
            var shippingOrderDetail = Context.TShippingOrderDetails.Find(id);

            // 如果找到了出库管理记录
            if (shippingOrderDetail != null)
            {
                // 查询对应的货位锁定明细记录
                var lockCells = Context.TShippingLockCells.Where(c => c.OrderDetailId == id).ToList();
                if (lockCells.Any())
                {
                    //// 将货位锁定明细记录添加到出库管理详情中
                    //List<TShippingLockCell> lockCells = new List<TShippingLockCell>();
                    //foreach (var item in lockCells)
                    //{
                    //    TShippingLockCell lockCell = new TShippingLockCell();
                    //    lockCell = Mapper.Map<TShippingLockCell>(item);

                    //    lockCells.Add(lockCell);
                    //}

                    shippingOrderDetail.LockCell = lockCells;
                }
            }

            return shippingOrderDetail;
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdTShippingOrderDetailState(ReceivingOrderDetailDto model)
        {
            var robjs = Context.TShippingOrderDetails.Where(s=>s.OrderSn==model.OrderSN).ToList();

            if (robjs != null && robjs.Count()!=0)
            {
                foreach (var robj in robjs)
                {
                    switch (model.state)
                    {
                        case 0:
                            var uobj = Context.TUsers.FirstOrDefault(x =>
                                x.Id == model.NowUserId && x.JobNo == model.JobNo);
                            if (uobj != null)
                            {
                                robj.SubmitUserId = model.NowUserId;
                                robj.SubmitUserName = model.NowUserRealName;
                                robj.SubmitDate = DateTime.Now;

                                //修改为：审核通过
                                robj.Status = 2;
                                Context.TShippingOrderDetails.Update(robj);
                                break;
                            }

                            return false;

                        case 1:
                            break;

                        case 2:
                            robj.ModifyUserId = model.NowUserId;
                            robj.ModifyUserName = model.NowUserRealName;
                            robj.ModifyDate = DateTime.Now;
                            //修改为：作业中
                            robj.Status = 3;
                            Context.TShippingOrderDetails.Update(robj);
                            break;

                        case 3:
                            robj.ModifyUserId = model.NowUserId;
                            robj.ModifyUserName = model.NowUserRealName;
                            robj.ModifyDate = DateTime.Now;
                            //修改为：已完成
                            robj.Status = 4;
                            Context.TShippingOrderDetails.Update(robj);
                            break;

                        default:
                            break;
                    }
                }

                return Context.SaveChanges() > 0;
            }

            return false;
        }

        /// <summary>
        /// 一键选定(弃用)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SelectTShippingOrderDetail(TShippingOrderDetail model)
        {
            var OrderDetail = Context.TShippingOrderDetails.FirstOrDefault(m =>
                m.MaterialId == model.MaterialId &&
                m.WarehouseId == model.WarehouseId && m.Qty == model.Qty);
            if (OrderDetail == null)
            {
                return false; // 找不到对应的出库管理记录，选定失败
            }
            // 设置其他相关字段值，例如物料分类、物料名称、物料批次等

            OrderDetail.MaterialName = model.MaterialName;
            OrderDetail.WarehouseName = model.WarehouseName;
            OrderDetail.Qty = model.Qty;
            OrderDetail.MaterialCode = model.MaterialCode;
           
            OrderDetail.ContractNo = model.ContractNo;
            OrderDetail.BillType = model.BillType;

            OrderDetail.SupplierId = model.SupplierId;
            OrderDetail.SupplierName = model.SupplierName;
            OrderDetail.AuditUserId = model.AuditUserId;
            OrderDetail.AuditUserName = model.AuditUserName;
            OrderDetail.Status = model.Status;
            // 保存修改
            Context.SaveChanges();

            // 创建新的TShippingLockCell实例并赋值
            List<TShippingLockCell> lockCells = new List<TShippingLockCell>();

            //库位
            var Cells = Context.TCells.FirstOrDefault(m => lockCells.Any(x => x.CellId == m.Id));
            //出库详细单
            var orderDetail =
                Context.TShippingOrderDetails.FirstOrDefault(m => lockCells.Any(x => x.OrderDetailId == m.Id));
            //库存
            var inventory = Context.TInventories.FirstOrDefault(m => lockCells.Any(x => x.InventoryId == m.Id));

            if (new TShippingLockCell().InventoryQty >= model.Qty)
            {
                var lockCell = new TShippingLockCell
                {
                    MaterialId = OrderDetail.MaterialId,
                    MaterialCode = model.MaterialCode,
                    MaterialName = model.MaterialName,
                    OrderDetailId = model.Id,
                    OutQty = OrderDetail.Qty,
                    CellName = Cells.Name,
                    WhId = OrderDetail.WarehouseId,
                    InventoryId = inventory.Id,
                    InventoryQty = inventory.AvailableQty,
                };
                lockCells.Add(lockCell);
            }
            else
            {
                // 根据出库数量创建多个TShippingLockCell实例并添加到列表中
                decimal? remainingQty = model.Qty;
                decimal? stockQuantity = inventory.AvailableQty;
                while (remainingQty > 0)
                {
                    var lockCellss = new TShippingLockCell
                    {
                        MaterialId = OrderDetail.MaterialId,
                        MaterialCode = model.MaterialCode,
                        MaterialName = model.MaterialName,
                        OrderDetailId = model.Id,
                        OutQty = OrderDetail.Qty,
                        CellName = Cells.Name,
                        WhId = OrderDetail.WarehouseId,
                        InventoryId = inventory.Id,
                        InventoryQty = Math.Min(stockQuantity ?? 0, remainingQty ?? 0),
                    };

                    lockCells.Add(lockCellss);

                    remainingQty -= stockQuantity; // 更新剩余数量
                }
            }

            Context.TShippingLockCells.AddRange(lockCells);

            return Context.SaveChanges() > 0;
        }

        /// <summary>
        /// 一键选定（弃用）
        /// </summary>
        /// <param name="qty"></param>
        /// <param name="inventoryId"></param>
        /// <param name="whId"></param>
        /// <param name="materialId"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TShippingLockCell> GetAllTShippingLockCell(TShippingOrderDetail model)
        {
            // 校验物料Id是否为空或无效
            if (model.MaterialId <= 0)
            {
                throw new ArgumentException("请选择物料");
            }

            // 校验数量是否为空或无效
            if (model.Qty <= 0)
            {
                throw new ArgumentException("请选择出库数量");
            }

            if (model.WarehouseId <= 0)
            {
                throw new ArgumentException("请选择仓库");
            }

            if (model.MaterialId <= 0)
            {
                throw new ArgumentException("请选择物料");
            }

            List<TShippingLockCell> selectedCells = new List<TShippingLockCell>();
            // 查询仓位明细表中符合条件的数据
            var query = from cell in Context.TShippingLockCells
                        where cell.InventoryQty >= model.Qty && cell.WhId == model.WarehouseId &&
                              cell.MaterialId == model.MaterialId

                        select cell;

            // 遍历查询结果，并将符合条件的仓位明细添加到返回列表中
            foreach (var cell in query)
            {
                selectedCells.Add(cell);
            }

            return selectedCells;
        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="status"></param>
        /// <param name="houseid"></param>
        /// <param name="name"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TShippingOrderDetail> GetAllTShippingOrderDetail(int? billType, int? houseid, string? name,
            int pageIndex, int pageSize, out int totalCount)
        {
            // 创建查询的基础列表，包含所有的 TShippingOrderDetail 记录
            var query = Context.TShippingOrderDetails.AsQueryable();

            // 根据传入的参数进行筛选
            if (billType.HasValue && billType.Value != 0)
            {
                query = query.Where(m => m.BillType == billType);
            }

            if (houseid.HasValue && houseid.Value != 0)
            {
                query = query.Where(m => m.WarehouseId == houseid);
            }

            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(m => m.MaterialName == name);
            }

            // 获取符合条件的总记录数
            totalCount = query.Count();

            // 对结果进行排序和分页
            var resultList = query.OrderByDescending(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            return resultList;
        }

        /// <summary>
        /// 根据物料Id返回批次号和数量
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public BatchNoMaxCount GetMaterialIdById(int materialId, string batchNO = null, int? qualityState = null, string warehouseCode = "", string areaCode = "", int? ownerId = null, int? supplierId = null, string produceFactory = "")
        {
            //数量
            try
            {
                //BatchNoMaxCount bc = new BatchNoMaxCount();

                //////找出该库存的所有批次号
                ////var materialKeyQuery = Context.TMaterialKeys;
                //var inventoryQuery = Context.TInventories;

                //var list=(from mk in materialKeyQuery
                //         join inv in inventoryQuery
                //         on mk.Id equals inv.MaterialKeyId
                //         where mk.MaterialId == materialId
                //         select new BatchNoMaxCountDTO ( mk.BatchNo,mk.Id)).Distinct().ToList();
                //bc.materialKeys = list;

                ////仓位状态 货架状态 巷道状态
                //var cellQuery = Context.TCells;
                //var shelfQuery = Context.TShelves;
                //var TInventoryQuery = (from inv in Context.TInventories
                //                       join cell in cellQuery
                //                       on inv.LocationId equals cell.Id
                //                       join slf in shelfQuery
                //                       on cell.ShelfId equals slf.Id                                   
                //                       where cell.Status == 1 && slf.Status == 1
                //                       select inv
                //                      ).ToList();

                //var invList = TInventoryQuery.Where(t => t.MaterialId == materialId && t.Status == 1 && t.IsLock == false).ToList();
                //if (!string.IsNullOrEmpty(batchNO))
                //{
                //    invList = invList.Where(t => t.BatchNo == batchNO).ToList();
                //}
                //if (qualityState != null)
                //{
                //    invList = invList.Where(t => t.QualityState == qualityState).ToList();
                //}
                //if (!string.IsNullOrEmpty(warehouseCode))
                //{
                //    invList = invList.Where(t => t.WarehouseCode == warehouseCode).ToList();
                //}
                //if (!string.IsNullOrEmpty(areaCode))
                //{
                //    invList = invList.Where(t => t.AreaCode == areaCode).ToList();
                //}
                //if (ownerId > 0)
                //{
                //    invList = invList.Where(t => t.OwnerId == ownerId).ToList();
                //}
                //if (supplierId > 0)
                //{
                //    invList = invList.Where(t => t.SupplierId == supplierId).ToList();
                //}
                //if (!string.IsNullOrEmpty(produceFactory))
                //{
                //    invList = invList.Where(t => t.ProduceFactory.Contains(produceFactory)).ToList();
                //}
                //decimal? sum = invList.Sum(t => t.AvailableQty);

                //List<int?> status = new List<int?>
                //{
                //    (int)EmBillStatus.Create,
                //    (int)EmBillStatus.Submit,
                //    (int)EmBillStatus.Pass,
                //};
                ////一键出库优先级最高
                //var shippingOrderDetailQuery = Context.TShippingOrderDetails.OrderByDescending(t => t.IsOnceOut);
                //var slcOdQuery = (from lockCell in Context.TShippingLockCells
                //                  join od in shippingOrderDetailQuery
                //                  on lockCell.OrderDetailId equals od.Id
                //                  select new { lockCell, od }
                //                ).ToList();
                //var slcOdQueryTest = slcOdQuery.ToList();
                //List<TShippingLockCell> lockCells = slcOdQuery.Select(x => x.lockCell).ToList();
                //List<TShippingOrderDetail> orderDetails = slcOdQuery.Select(x => x.od).ToList();
                //orderDetails = orderDetails.Where(od => od.MaterialId == materialId && status.Contains(od.Status)).ToList();
                //lockCells = lockCells.Where(loc => loc.MaterialId == materialId).ToList();
                //slcOdQuery = (from lockCell in lockCells
                //                join od in orderDetails
                //                on lockCell.OrderDetailId equals od.Id
                //                select new { lockCell, od }
                //        ).ToList();
                

                ////剔除被锁定的库存
                //var lockInvIdQuery = (from lockCell in lockCells
                //                      join od in orderDetails
                //                      on lockCell.OrderDetailId equals od.Id
                //                      select lockCell.InventoryId
                //            ).Distinct().ToList();
                //int lockInvCount = lockInvIdQuery.Count();
                //if (lockInvCount > 0)
                //{
                //    invList = invList.Where(t => !lockInvIdQuery.ToList().Contains(t.Id)).ToList();
                //}
                ////查出所有匹配的库存
                //List<TInventory> TInventoryList = invList.OrderBy(x => x.LocationDepth)
                //                                        .ThenBy(x => x.InStockShortDate)
                //                                        .ThenByDescending(x => x.AvailableQty)
                //                                        .ThenBy(x => x.LocationLineNo)
                //                                        .ThenBy(x => x.LocationLayerNo)
                //                                        .ThenBy(x => x.LocationColumnNo).ToList();
                ////库存可用数量
                //decimal totalTInventoryCount = TInventoryList.Sum(t => t.AvailableQty.GetValueOrDefault());
                ////当前物料已出库多少

                //bc.MaxCount = totalTInventoryCount;
                return null;

            }
            catch (Exception ex)
            {
                throw ex;
            }
     
            //BatchNoMaxCount bc = new BatchNoMaxCount();
            ////物料批次
            //var mkobj = Context.TMaterialKeys.FirstOrDefault(x => x.MaterialId == mid);
            ////库存数量
            //var iobj = Context.TInventories.Where(x => x.MaterialId == mid);
            //if (iobj.Count() <= 0)
            //{
            //    return bc;
            //}

            //if (mkobj != null)
            //{
            //    bc.BatchNO.Add(mkobj.BatchNo);
            //}

            //if (iobj != null)
            //{
            //    foreach (var item in iobj.ToList())
            //    {
            //        bc.MaxCount += item.AvailableQty;
            //    }
            //}

            //return bc;
        }
         
        /// <summary>
        /// 一键选定
        /// </summary>
        /// <param name="materid">物料Id</param>
        /// <param name="count">出库数量</param>
        /// <param name="whid">库房Id</param>
        /// <param name="areaid">库区Id</param>
        /// <param name="supid">供应商Id</param>
        /// <param name="owid">货主Id</param>
        /// <returns></returns>
        public List<TInventory> GetAllTShippingLockCell(int materid, int count, int whid, int areaid, int supid,
            int owid)
        {
            //var shippinglockcell=Context.TShippingLockCells.Where(x=>x.)
            var ilist = Context.TInventories.Where(x => x.MaterialId == materid);
            ilist = ilist.Where(x => x.AvailableQty != 0 && x.Status==1);
            ilist = ilist.OrderBy(x => x.BatchNo);
            //库房
            if (whid != 0)
            {
                ilist = ilist.Where(x => x.WarehouseId == whid);
            }

         

            //供应商
            if (supid != 0)
            {
                ilist = ilist.Where(x => x.SupplierId == supid);
            }          

            List<TInventory> list = new List<TInventory>();
            //收货的数量
            foreach (var item in ilist)
            {
                //decimal? outqty = count - item.AvailableQty;
                if (count == item.AvailableQty)
                {
                    //如果要出库的数量等于该库存的数量则直接返回
                    item.OutQty = item.AvailableQty;
                    list.Add(item);
                    return list;
                }
                else if (count > item.AvailableQty)
                {
                    item.OutQty = item.AvailableQty;
                    list.Add(item);
                    count = Convert.ToInt32(count - item.OutQty);
                }
                else if (count < item.AvailableQty)
                {
                    item.OutQty = count;
                    list.Add(item);
                    return list;
                }
            }
            
            return list;
        }

        /// <summary>
        /// 获取商品详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<TShippingGoodsDetail> GetOneTShippingGoodsDetail(int id, int pageIndex, int pageSize, out int totalCount)
        {
            var order = Context.TShippingOrderDetails.Find(id);
            if (order == null)
            {
                totalCount = 0;
                // 订单不存在时返回一个空的列表
                return new List<TShippingGoodsDetail>();
            }
            var details = Context.TShippingGoodsDetails.Where(m => m.OrderDetailId == order.Id).ToList();
            // 获取符合条件的总记录数
            totalCount = details.Count();

            // 对结果进行排序和分页
            var resultList = details.OrderBy(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();
            return resultList;
        }

        public List<TShippingGoodsDetail> GetByNameShippingGoodsDetail(string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var query = Context.TShippingGoodsDetails.AsQueryable();
            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(m => m.MaterialName == name);
            }
            totalCount = query.Count();

            // 对结果进行排序和分页
            var resultList = query.OrderBy(m => m.CreateDate)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            return resultList;
        }

        public List<GetChukuDanDTO> GetAllTShippingOrderDetailPlus(int? billType, int? houseid, string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var listNoPage = Context.TShippingOrderDetails.AsEnumerable();
            if (billType != null)
                listNoPage = listNoPage.Where(s=>s.BillType==billType);
            if(houseid!=null)
                listNoPage=listNoPage.Where(s=>s.WarehouseId==houseid);
            if (name != null)
                listNoPage = listNoPage.Where(s => s.MaterialName == name);
            var items = listNoPage.OrderByDescending(s => s.CreateDate).GroupBy(s => s.OrderSn);
            var list= items.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            totalCount = items.Count();
            List<GetChukuDanDTO> resList = new List<GetChukuDanDTO>();
            foreach (var item in list)
            {
                var key = item.Key;
                var lockCellList = new List<TShippingLockCell>();
                var shippoutList = new List<TShippingOrderDetail>();
                foreach (var value in item)
                {
                    var lockCell = Context.TShippingLockCells.Where(s => s.OrderDetailId == value.Id);
                    foreach (var item1 in lockCell)
                    {
                        lockCellList.Add(item1);
                    }
                    shippoutList.Add(value);
                }
                resList.Add(new GetChukuDanDTO()
                {
                    Status = GetStatus(shippoutList),
                    OrderSn = key,
                    CreateTime = shippoutList[0].CreateDate,
                    Sum = shippoutList.Sum(s=>s.Qty),
                    CreateUserName= shippoutList[0].CreateUserName,
                    AuditUserName= shippoutList[0].AuditUserName,
                    shippingOrders = lockCellList,
                });
            }
            return resList;
        }
        private string GetStatus(List<TShippingOrderDetail> shippingGoods)
        {
            int status = 4;
            string str = "未知状态";
            foreach (var item in shippingGoods)
            {
                if (item.Status != 4)
                {
                    if (item.Status == 0)
                    {
                        status = 0;
                        break;
                    }
                    else if (item.Status == 1)
                    {
                        status = 1;
                        break;
                    }
                    else if (item.Status == 2)
                    {
                        status = 2;
                        break;
                    }
                    else if (item.Status == 3)
                    {
                        status = 3;
                        break;
                    }
                }
            }
            if (status == 0)
            {
                str = "创建";
                return str;
            } else if (status == 1)
            {
                str = "提交";
                return str;
            } else if (status == 2)
            {
                str = "审核通过";
                return str;
            }else if (status==3)
            {
                str = "作业中";
                return str;
            }else if (status == 4)
            {
                str = "已完成";
                return str;
            }
            return str;
        }
    }
}